package com.csust.automaticteach.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csust.automaticteach.app.teacher.KnowledgeGraphGenerateApp;
import com.csust.automaticteach.model.enums.GenerateQuestionStatusEnum;
import com.csust.automaticteach.exception.ErrorCode;
import com.csust.automaticteach.exception.ThrowUtils;
import com.csust.automaticteach.model.dto.knowledgegraph.KnowledgeGraphAddRequest;
import com.csust.automaticteach.model.dto.knowledgegraph.KnowledgeGraphQueryRequest;
import com.csust.automaticteach.model.dto.knowledgegraph.response.GraphOption;
import com.csust.automaticteach.model.entity.GenerateTeach;
import com.csust.automaticteach.model.entity.KnowledgeGraph;
import com.csust.automaticteach.model.entity.User;
import com.csust.automaticteach.model.vo.knowledgegraph.KnowledgeGraphVO;
import com.csust.automaticteach.service.GenerateTeachService;
import com.csust.automaticteach.service.KnowledgeGraphService;
import com.csust.automaticteach.mapper.KnowledgeGraphMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

import static com.csust.automaticteach.constant.OrderConstant.ASC;

/**
* @author 钰玟
* @description 针对表【t_knowledge_graph(知识图谱表)】的数据库操作Service实现
* @createDate 2025-07-19 12:26:44
*/
@Service
public class KnowledgeGraphServiceImpl extends ServiceImpl<KnowledgeGraphMapper, KnowledgeGraph>
    implements KnowledgeGraphService{
    @Resource
    private KnowledgeGraphGenerateApp knowledgeGraphGenerateApp;
    @Resource
    private GenerateTeachService generateTeachService;
    @Override
    public Boolean generateKnowledgeGraph(KnowledgeGraphAddRequest knowledgeGraphAddRequest, User loginUser) {
        //1.
        KnowledgeGraph knowledgeGraph = new KnowledgeGraph();
        //2.提取参数  二选一
        Long generateTeachId = knowledgeGraphAddRequest.getGenerateTeachId();
        String outline = knowledgeGraphAddRequest.getOutline();
        if (outline != null) {
            knowledgeGraph.setUploadContent(outline);
        }
        if (generateTeachId != null) {
            knowledgeGraph.setTeachId(generateTeachId);
            //选择的是已有的课程大纲
            GenerateTeach generateTeach = generateTeachService.getById(generateTeachId);
            outline = generateTeach.getContent();
        }
        //3.调用生成知识图谱的接口
        String chatId = UUID.randomUUID().toString();
        String content = knowledgeGraphGenerateApp.doGenerate(outline, chatId);
        GraphOption graphOption = this.parseContent(content);
        //4. 获取标题和描述
        graphOption.getNodes().get(0);
        String title = graphOption.getNodes().get(0).getName();
        String description = graphOption.getNodes().get(1).getName();
        knowledgeGraph.setTitle(title+"的知识图谱");
        knowledgeGraph.setDescription(description + "...");
        //5.保存知识图谱
        knowledgeGraph.setUserId(loginUser.getId());
        knowledgeGraph.setContent(content);
        knowledgeGraph.setStatus(GenerateQuestionStatusEnum.DRAFT.getValue());
        boolean saved = this.saveOrUpdate(knowledgeGraph);
        ThrowUtils.throwIf(!saved, ErrorCode.OPERATION_ERROR);
        return true;
    }
    @Override
    public QueryWrapper<KnowledgeGraph> getKnowledgeGraphQueryWrapper(KnowledgeGraphQueryRequest knowledgeGraphQueryRequest) {
        Long id = knowledgeGraphQueryRequest.getId();
        Long userId = knowledgeGraphQueryRequest.getUserId();
        String sortField = knowledgeGraphQueryRequest.getSortField();
        String sortOrder = knowledgeGraphQueryRequest.getSortOrder();

        QueryWrapper<KnowledgeGraph> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull( id), "id", id);
        queryWrapper.eq(ObjUtil.isNotNull( userId), "userId", userId);
        queryWrapper.orderBy(ObjUtil.isNotEmpty(sortField),sortOrder.equals(ASC), sortField);

        return queryWrapper;
    }

    @Override
    public KnowledgeGraphVO getKnowledgeGraphVO(KnowledgeGraph record) {
        KnowledgeGraphVO knowledgeGraphVO = new KnowledgeGraphVO();
        BeanUtil.copyProperties(record, knowledgeGraphVO);
        if(record.getUploadContent()!=null){
            knowledgeGraphVO.setUploadContent(true);
        }
        GraphOption graphOption = this.parseContent(record.getContent());
        knowledgeGraphVO.setGraphOption(graphOption);
        return knowledgeGraphVO;
    }

    @Override
    public List<KnowledgeGraphVO> getKnowledgeGraphVOList(List<KnowledgeGraph> records) {
        return records.stream().map(this::getKnowledgeGraphVO).toList();
    }

    @Override
    public GraphOption parseContent(String content) {
        return JSONUtil.toBean(content, GraphOption.class);
        // 解析 JSON 字符串为 JSONObject
//        JSONObject jsonObject = JSONUtil.parseObj(content);
//        // 获取 "nodes" 数组
//        JSONArray nodes = jsonObject.getJSONArray("nodes");
        //解析前两个name 为title 和  description

        // 获取 "edges" 数组
//        JSONArray edges = jsonObject.getJSONArray("edges");
//        for (Object edge : edges) {
//            JSONObject edgeObj = (JSONObject) edge;
//            System.out.println(" - Source: " + edgeObj.getStr("source") + ", Target: " + edgeObj.getStr("target"));
//        }
    }


}




